package com.junmeng.jdemo.recycler.chat.viewstub;

import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;

import androidx.annotation.NonNull;

import com.junmeng.jdemo.R;
import com.example.common.recycler.base.BaseBindView;
import com.example.common.recycler.base.BindViewStore;
import com.example.common.recycler.base.IBIndViewManager;
import com.example.common.recycler.common.RecyclerViewHolder;

import java.util.List;

public class ChatBindViewManager<T> implements IBIndViewManager<T, RecyclerViewHolder, BaseChatBindView> {
    BindViewStore<BaseChatBindView> bindViewStore = new BindViewStore<>();

    SparseArray<Integer> resId = new SparseArray<>();

    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Log.i("123456","onCreateViewHolder:viewType="+viewType);
        RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(getItemView(parent, viewType));
        return recyclerViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position, @NonNull T t, @NonNull List<Object> payloads) {
        bindViewStore.getBindView(t.getClass().hashCode()).bindViewData(holder, position, t, payloads);
    }

    @Override
    public void onViewRecycled(@NonNull RecyclerViewHolder holder, @NonNull T t) {
        int code = t.getClass().hashCode();
        BaseBindView bindView = bindViewStore.getBindView(code);
        if (bindView == null) {
            return;
        }
        bindView.onViewRecycled(holder);
    }

    @Override
    public void register(@NonNull BaseChatBindView bindView) {
        bindViewStore.putBindView(bindView.itemBeanType.hashCode(), bindView);
    }

    public View getItemView(@NonNull ViewGroup parent, int viewType) {
        int layoutResId = resId.get(viewType);
        View itemView = LayoutInflater.from(parent.getContext()).inflate(layoutResId, parent, false);
        try {
            ViewStub viewStub = itemView.findViewById(R.id.stub_content);
            viewStub.setLayoutResource(viewType);
            viewStub.inflate();//第二次执行会抛异常
        } catch (Exception e) {
            e.printStackTrace();
        }

        return itemView;
    }

    @Override
    public int getItemViewType(int position, @NonNull T t) {
        int type = t.getClass().hashCode();
        int contentResId = bindViewStore.getBindView(type).getItemContentLayoutResId(t);
        int layoutResId = bindViewStore.getBindView(type).getItemLayoutResId(t);
        resId.put(contentResId, layoutResId);
        Log.i("123456","getItemViewType:position="+position+",contentResId="+contentResId);
        return contentResId;
    }
}
